<template>
  <a-modal
    style="top: 1px;"
    :title="title"
    :width="width"
    v-model="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :maskClosable="false"
  >
    <template #footer>
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button key="submit" v-show="oktext" type="primary" :loading="loading" @click="handleOk">
        {{oktext}}
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div>
        <a-form :model="main" :rules="rules" ref="formRef" layout="horizontal">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="支付日期" :label-col="labelCol" :wrapper-col="wrapperCol" prop="payment_date">
                <a-date-picker
                  :value-format="dateFormat"
                  v-model="main.payment_date"
                  style="width: 100%"
                  :get-popup-container="trigger => trigger.parentNode"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="支付金额" :label-col="labelCol" :wrapper-col="wrapperCol" prop="amount">
                <a-input-number v-model="main.amount" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="所属月份" :label-col="labelCol" :wrapper-col="wrapperCol" prop="bill_month">
                <a-date-picker
                  :value-format="monthFormat"
                  picker="month"
                  v-model="main.bill_month"
                  style="width: 100%"
                  :get-popup-container="trigger => trigger.parentNode"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="关联发票号" :label-col="labelCol" :wrapper-col="wrapperCol" prop="id_invoice">
                <a-select
                  allowClear
                  mode="multiple"
                  showSearch
                  optionFilterProp="children"
                  v-model="main.id_invoice"
                >
                  <a-select-option v-for="c of invoices" :key="c.id" :value="c.id">{{c.invoice_no}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="入帐公司" :label-col="labelCol" :wrapper-col="wrapperCol" prop="id_company">
                <a-select v-model="main.id_company">
                  <a-select-option v-for="c of companies" :key="c.id" :value="c.id">{{c.title}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item label="备注" :label-col="labelCol2" :wrapper-col="wrapperCol" prop="memo">
                <a-input v-model="main.memo" type="textarea" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div></div>
    </a-spin>
  </a-modal>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { postAction } from '@/utils/request';
import { message } from 'ant-design-vue';
import { pick } from 'lodash';

// 定义 props
const props = defineProps({
  id_client: {
    type: [String, Number],
    required: true
  },
  invoices: {
    type: Array,
    default: () => []
  }
});

// 定义 emits
const emit = defineEmits(['sync']);
// 表单引用
const formRef = ref(null);

// 响应式数据
const loading = ref(false);
const title = ref('新增');
const width = ref('90%');
const visible = ref(false);
const dateFormat = ref('YYYY-MM-DD');
const monthFormat = ref('YYYY-MM');
const main = reactive({
  id: undefined,
  payment_date: undefined,
  bill_month: undefined,
  id_invoice: undefined,
  name: undefined,
  amount: 0,
  memo: '',
  id_client: props.id_client,
  id_company: undefined
});
const readOnly = ref(true);
const oktext = ref('保存');
const labelCol = {
  xs: { span: 24 },
  sm: { span: 10 }
};
const wrapperCol = {
  xs: { span: 24 },
  sm: { span: 14 }
};
const labelCol2 = {
  xs: { span: 20 },
  sm: { span: 6 }
};
const confirmLoading = ref(false);
const feeItems = ref([]);
const feeData = ref({});
const table = {
  main: 'YG_payment'
};
const url = {
  getDataBySql: '/reportConfig/config/getDataBySql'
};

// 表单验证规则
const rules = reactive({
  payment_date: [
    { required: true, message: '支付日期不能为空', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '支付金额不能为空', trigger: 'blur' },
    { validator: checkNumber, trigger: 'blur' }
  ],
  bill_month: [
    { required: true, message: '所属月份不能为空', trigger: 'blur' }
  ]
});

// 方法
const add = () => {
  main.id = undefined;
  edit({});
};

const edit = (record) => {
  readOnly.value = false;
  if (record && record.id) {
    main.id = record.id;
    title.value = '编辑';
  }
  formRef.value?.resetFields();
  let tmp = record.id_invoice && record.id_invoice.split(',').map((id) => parseInt(id));
  record.id_invoice = tmp;
  Object.assign(main, pick(record, Object.keys(main)));
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

const handleCancel = () => {
  close();
};

const handleOk = () => {
  if (readOnly.value) {
    close();
    return;
  }
  save();
};

const save = async () => {
  if (!formRef.value) return;
  try {
    const values = await formRef.value.validate();
    const sql = savePaymentSql(values);
    console.log(sql);
    const res = await postAction(url.getDataBySql, { sql });
    if (res && res.success) {
      await postAction(url.getDataBySql, { sql: updateClientProfitSql(props.id_client) });
      message.success('保存成功！');
      close();
      emit('sync');
    } else {
      message.error(res.message || '保存失败');
    }
  } catch (error) {
    message.warning('表单信息验证失败');
  }
};

const checkNumber = (rule, value, callback) => {
  if (value !== undefined && value !== null && isNaN(Number(value))) {
    callback('请输入数字!');
  } else {
    callback();
  }
};

const updateClientProfitSql = (id_client) => {
  return `update c set c.paid_amount=t.paid_amount from YG_client c join (select 1 xx)d on c.id=${id_client} cross apply(select sum(amount)paid_amount from YG_payment r where c.id=r.id_client)t`;
};

const savePaymentSql = (values) => {
  const fields = { ...values, ...getCommonFields(false) };
  fields.id_client = props.id_client;
  let sql = '';
  const keys = [];
  for (const key in fields) {
    if (key !== 'id' && fields[key] !== undefined) {
      keys.push(key);
    }
  }
  if (main.id) {
    const updateArr = keys.map((key) => `${key}='${fields[key]}'`);
    const updateCmd = updateArr.join(',');
    sql = `update ${table.main} set ${updateCmd} where id=${main.id}`;
  } else {
    const columns = keys.join(',');
    const valuesStr = keys.map((key) => `'${fields[key]}'`).join(',');
    sql = `insert into ${table.main} (${columns}) values (${valuesStr}); select @@IDENTITY id;`;
  }
  return sql;
};

// 假设 getCommonFields 函数在别处定义，这里给出空实现
const getCommonFields = (flag) => {
  return {};
};
</script>
